<script setup>
import { ref, onMounted } from 'vue'

const reminderList = ref([])
const showAddModal = ref(false)
const newReminder = ref({
  title: '',
  time: '',
  date: '',
  repeat: [],
  note: '',
  active: true
})

const repeatOptions = [
  { value: 'once', label: '仅一次' },
  { value: 'daily', label: '每天' },
  { value: 'weekly', label: '每周' },
  { value: 'monthly', label: '每月' }
]

const weekOptions = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']

onMounted(() => {
  // 从本地存储加载提醒列表
  const savedReminders = uni.getStorageSync('healthReminders') || []
  reminderList.value = savedReminders
})

function openAddModal() {
  // 设置默认日期和时间为当前
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  
  newReminder.value = {
    title: '',
    time: `${hours}:${minutes}`,
    date: `${year}-${month}-${day}`,
    repeat: ['once'],
    note: '',
    active: true
  }
  
  showAddModal.value = true
}

function closeAddModal() {
  showAddModal.value = false
}

function addReminder() {
  if (!newReminder.value.title) {
    uni.showToast({
      title: '请输入提醒标题',
      icon: 'none'
    })
    return
  }
  
  // 创建新提醒
  const reminder = {
    id: Date.now(),
    ...newReminder.value,
    createdAt: new Date().toISOString()
  }
  
  // 添加到列表
  reminderList.value.unshift(reminder)
  
  // 保存到本地存储
  uni.setStorageSync('healthReminders', reminderList.value)
  
  // 设置系统提醒（实际项目中可能需要调用原生API）
  setSystemReminder(reminder)
  
  uni.showToast({
    title: '添加成功',
    icon: 'success'
  })
  
  closeAddModal()
}

function toggleReminder(reminder) {
  reminder.active = !reminder.active
  
  // 更新本地存储
  uni.setStorageSync('healthReminders', reminderList.value)
  
  // 更新系统提醒状态
  if (reminder.active) {
    setSystemReminder(reminder)
    uni.showToast({
      title: '已开启提醒',
      icon: 'success'
    })
  } else {
    cancelSystemReminder(reminder)
    uni.showToast({
      title: '已关闭提醒',
      icon: 'none'
    })
  }
}

function deleteReminder(id) {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条提醒吗？',
    success: (res) => {
      if (res.confirm) {
        // 找到要删除的提醒
        const reminderToDelete = reminderList.value.find(item => item.id === id)
        
        // 取消系统提醒
        if (reminderToDelete) {
          cancelSystemReminder(reminderToDelete)
        }
        
        // 从列表中删除
        reminderList.value = reminderList.value.filter(item => item.id !== id)
        
        // 更新本地存储
        uni.setStorageSync('healthReminders', reminderList.value)
        
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
      }
    }
  })
}

// 设置系统提醒（模拟实现，实际项目中需要调用原生API）
function setSystemReminder(reminder) {
  console.log('设置系统提醒:', reminder)
  // 实际项目中，这里需要调用系统的提醒/通知API
  // 例如在App中可能需要调用原生的本地通知功能
}

// 取消系统提醒（模拟实现）
function cancelSystemReminder(reminder) {
  console.log('取消系统提醒:', reminder)
  // 实际项目中，这里需要调用系统的取消提醒/通知API
}

// 获取重复类型标签
function getRepeatLabel(type) {
  const option = repeatOptions.find(opt => opt.value === type)
  return option ? option.label : ''
}

// 切换重复类型
function toggleRepeatType(type) {
  // 如果是单选类型（once, daily, monthly），则替换当前值
  if (['once', 'daily', 'monthly'].includes(type)) {
    newReminder.value.repeat = [type]
  } 
  // 如果是weekly，则可以多选星期几
  else if (type === 'weekly') {
    // 如果当前不是weekly模式，则清空并设置为weekly
    if (!newReminder.value.repeat.includes('weekly')) {
      newReminder.value.repeat = ['weekly']
    }
    // 如果已经是weekly模式，则保持不变
  }
}

// 切换星期选项
function toggleWeekday(day) {
  // 确保当前是weekly模式
  if (!newReminder.value.repeat.includes('weekly')) {
    newReminder.value.repeat = ['weekly']
  }
  
  const index = newReminder.value.repeat.indexOf(day)
  if (index > -1) {
    // 如果已选中，则取消选中
    newReminder.value.repeat.splice(index, 1)
  } else {
    // 如果未选中，则添加选中
    newReminder.value.repeat.push(day)
  }
}

// 检查星期几是否被选中
function isWeekdaySelected(day) {
  return newReminder.value.repeat.includes(day)
}

// 检查重复类型是否被选中
function isRepeatTypeSelected(type) {
  return newReminder.value.repeat.includes(type)
}

// 获取提醒的重复描述
function getReminderRepeatDesc(reminder) {
  if (reminder.repeat.includes('once')) {
    return '仅一次'
  } else if (reminder.repeat.includes('daily')) {
    return '每天'
  } else if (reminder.repeat.includes('monthly')) {
    return '每月'
  } else if (reminder.repeat.includes('weekly')) {
    // 获取选中的星期几
    const selectedDays = weekOptions.filter(day => reminder.repeat.includes(day))
    if (selectedDays.length === 0) {
      return '每周'
    } else {
      return selectedDays.join('、')
    }
  }
  return ''
}
</script>

<template>
  <view class="container">
    <view class="header">
      <view class="title">健康提醒</view>
      <view class="subtitle">设置健康相关的提醒事项</view>
    </view>
    
    <view class="action-bar">
      <button class="add-btn" @click="openAddModal">添加提醒</button>
    </view>
    
    <view v-if="reminderList.length === 0" class="empty-state">
      <view class="empty-icon">⏰</view>
      <view class="empty-text">暂无提醒事项</view>
      <view class="empty-subtext">点击上方按钮添加提醒</view>
    </view>
    
    <view v-else class="reminder-list">
      <view 
        v-for="reminder in reminderList" 
        :key="reminder.id"
        class="reminder-item"
      >
        <view class="reminder-toggle">
          <switch 
            :checked="reminder.active" 
            @change="toggleReminder(reminder)" 
            color="#4caf50"
          />
        </view>
        
        <view class="reminder-content" :class="{ 'inactive': !reminder.active }">
          <view class="reminder-title">{{ reminder.title }}</view>
          
          <view class="reminder-info">
            <view class="reminder-time">{{ reminder.time }}</view>
            <view class="reminder-repeat">{{ getReminderRepeatDesc(reminder) }}</view>
          </view>
          
          <view v-if="reminder.note" class="reminder-note">{{ reminder.note }}</view>
        </view>
        
        <view class="reminder-actions">
          <view class="delete-btn" @click="deleteReminder(reminder.id)">删除</view>
        </view>
      </view>
    </view>
    
    <!-- 添加提醒弹窗 -->
    <view v-if="showAddModal" class="modal-overlay">
      <view class="modal-content">
        <view class="modal-header">
          <view class="modal-title">添加提醒</view>
          <view class="modal-close" @click="closeAddModal">×</view>
        </view>
        
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">提醒标题</text>
            <input 
              class="input" 
              v-model="newReminder.title" 
              placeholder="请输入提醒标题，如：服药提醒"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">提醒时间</text>
            <picker 
              mode="time" 
              :value="newReminder.time"
              @change="e => newReminder.time = e.detail.value"
              class="picker"
            >
              <view class="picker-value">{{ newReminder.time }}</view>
            </picker>
          </view>
          
          <view class="form-item">
            <text class="form-label">开始日期</text>
            <picker 
              mode="date" 
              :value="newReminder.date"
              @change="e => newReminder.date = e.detail.value"
              class="picker"
            >
              <view class="picker-value">{{ newReminder.date }}</view>
            </picker>
          </view>
          
          <view class="form-item">
            <text class="form-label">重复方式</text>
            <view class="repeat-options">
              <view 
                v-for="option in repeatOptions" 
                :key="option.value"
                :class="['repeat-option', { active: isRepeatTypeSelected(option.value) }]"
                @click="toggleRepeatType(option.value)"
              >
                {{ option.label }}
              </view>
            </view>
            
            <!-- 如果选择了每周，显示星期选择 -->
            <view v-if="isRepeatTypeSelected('weekly')" class="weekday-selector">
              <view 
                v-for="(day, index) in weekOptions" 
                :key="index"
                :class="['weekday-item', { active: isWeekdaySelected(day) }]"
                @click="toggleWeekday(day)"
              >
                {{ day.substring(1) }}
              </view>
            </view>
          </view>
          
          <view class="form-item">
            <text class="form-label">备注</text>
            <textarea 
              class="textarea" 
              v-model="newReminder.note" 
              placeholder="添加备注（选填）"
            />
          </view>
        </view>
        
        <view class="modal-footer">
          <button class="cancel-btn" @click="closeAddModal">取消</button>
          <button class="confirm-btn" @click="addReminder">确认</button>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  margin-bottom: 30rpx;
  
  .title {
    font-size: 40rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }
  
  .subtitle {
    font-size: 28rpx;
    color: #666;
  }
}

.action-bar {
  margin-bottom: 30rpx;
  
  .add-btn {
    background-color: #4caf50;
    color: #fff;
    font-size: 28rpx;
    padding: 15rpx 0;
    border-radius: 8rpx;
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  
  .empty-icon {
    font-size: 80rpx;
    margin-bottom: 20rpx;
  }
  
  .empty-text {
    font-size: 32rpx;
    color: #333;
    margin-bottom: 10rpx;
  }
  
  .empty-subtext {
    font-size: 26rpx;
    color: #999;
  }
}

.reminder-list {
  .reminder-item {
    display: flex;
    background-color: #fff;
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
  }
  
  .reminder-toggle {
    margin-right: 20rpx;
    display: flex;
    align-items: center;
  }
  
  .reminder-content {
    flex: 1;
    
    &.inactive {
      opacity: 0.5;
    }
    
    .reminder-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .reminder-info {
      display: flex;
      margin-bottom: 10rpx;
      
      .reminder-time {
        font-size: 28rpx;
        color: #666;
        margin-right: 20rpx;
      }
      
      .reminder-repeat {
        font-size: 26rpx;
        color: #999;
      }
    }
    
    .reminder-note {
      font-size: 26rpx;
      color: #666;
      line-height: 1.4;
    }
  }
  
  .reminder-actions {
    display: flex;
    align-items: center;
    
    .delete-btn {
      font-size: 26rpx;
      color: #f44336;
      padding: 6rpx 12rpx;
    }
  }
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.modal-content {
  width: 90%;
  max-height: 80vh;
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #eee;
  
  .modal-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .modal-close {
    font-size: 40rpx;
    color: #999;
    line-height: 1;
  }
}

.modal-body {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.form-item {
  margin-bottom: 25rpx;
  
  .form-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
    display: block;
  }
  
  .input, .picker {
    border: 1px solid #ddd;
    border-radius: 8rpx;
    padding: 15rpx;
    font-size: 28rpx;
    width: 100%;
    box-sizing: border-box;
    
    .picker-value {
      color: #333;
    }
  }
  
  .textarea {
    width: 100%;
    height: 150rpx;
    border: 1px solid #ddd;
    border-radius: 8rpx;
    padding: 15rpx;
    font-size: 28rpx;
    box-sizing: border-box;
  }
}

.repeat-options {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15rpx;
  
  .repeat-option {
    padding: 10rpx 20rpx;
    border: 1px solid #ddd;
    border-radius: 8rpx;
    font-size: 26rpx;
    color: #666;
    margin-right: 15rpx;
    margin-bottom: 15rpx;
    
    &.active {
      background-color: #4caf50;
      color: #fff;
      border-color: #4caf50;
    }
  }
}

.weekday-selector {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15rpx;
  
  .weekday-item {
    width: 70rpx;
    height: 70rpx;
    border-radius: 50%;
    border: 1px solid #ddd;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 26rpx;
    color: #666;
    
    &.active {
      background-color: #4caf50;
      color: #fff;
      border-color: #4caf50;
    }
  }
}

.modal-footer {
  display: flex;
  padding: 20rpx 30rpx;
  border-top: 1px solid #eee;
  
  .cancel-btn, .confirm-btn {
    flex: 1;
    margin: 0 10rpx;
    font-size: 28rpx;
    padding: 15rpx 0;
  }
  
  .cancel-btn {
    background-color: #f5f5f5;
    color: #666;
  }
  
  .confirm-btn {
    background-color: #4caf50;
    color: #fff;
  }
}
</style>